package net.luohuasheng.bee.proxy.core.utils;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ClassUtils {

    /**
     * classloader内相关类是否存在
     *
     * @param name 类名
     * @return 存在则返回true 否则返回 false
     */
    public static boolean isPresent(String name) {
        try {
            Thread.currentThread().getContextClassLoader().loadClass(name);
            return true;
        } catch (ClassNotFoundException e) {
            return false;
        }
    }

    private static List<Field> getAllFields(Class<?> clazz) {
        List<Field> result = new ArrayList<>();
        Field[] fields = clazz.getDeclaredFields();
        Collections.addAll(result, fields);
        Class<?> superClass = clazz.getSuperclass();
        if (superClass == Object.class) {
            return result;
        }
        result.addAll(getAllFields(superClass));
        return result;
    }

    public static List<Field> getAllFieldsExcludeTransient(Class<?> clazz) {
        List<Field> result = new ArrayList<>();
        List<Field> list = getAllFields(clazz);
        for (Field field : list) {
            if (Modifier.isTransient(field.getModifiers())) {
                continue;
            }
            result.add(field);
        }
        return result;
    }

}
